<template>
  <a-modal v-model:visible="visible" title="设置多账户出价" width="800px" @ok="save">
    <div class="modal-content">
      <div v-if="!AccountItems.length" class="empty-accounts">暂无可配置的账户</div>
      <div v-else class="account-list">
        <AccountTemplate @update:active="accountChange">
          <template #default>
            <CampaignBid
              :key="AccountItems[accountIdIndex]._id"
              v-model="converBidMap[AccountItems[accountIdIndex]._id]"
              :minBid="3"
              :maxBid="100"
              :precision="0"
              :showRandomBid="false"
              :showGradientBid="false"
            />
          </template>
        </AccountTemplate>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, provide } from "vue";
import AccountTemplate from "@/pages/NewBatchCreateAd/components/common/MultiAccountTemplate.vue";
import CampaignBid from "@/pages/NewBatchCreateAd/components/common/CampaignBid.vue";
import _ from "lodash";
import { batchCreateAdStore } from "@/pages/NewBatchCreateAd/store/batchCreateAdStore";
const store = batchCreateAdStore();
const { AccountItems } = store;
provide("accounts", AccountItems);

const visible = ref(false);

const accountIdIndex = ref(0);
const accountChange = (index: number) => {
  accountIdIndex.value = index;
};

const obj = store.Plan && store.Plan.converBidMap ? store.Plan.converBidMap : {};
const converBidMap = ref(_.cloneDeep(obj));

// 判断obj的key是否在AccountItems中，不在则删除
Object.keys(obj).forEach((key: any) => {
  const numKey = parseInt(key);
  if (!AccountItems.some((account: any) => account._id === numKey)) {
    delete converBidMap.value[key];
  }
});

// 确保所有账号都有默认出价设置
AccountItems.forEach((account: any) => {
  if (!converBidMap.value[account._id]) {
    converBidMap.value[account._id] = { type: "NORMAL_BID", value: 3 };
  }
});

// 确认按钮处理
const save = () => {
  store.Plan.converBidMap = converBidMap.value;
  visible.value = false;
};

const show = () => {
  visible.value = true;
};

defineExpose({
  show,
});
</script>

<style scoped lang="less"></style>
